import GROUP_DATA from '../../utils/groups.js'
import storage from '../../utils/storage.js'

Page({
  data: {
    groupId: '',
    currentWordIndex: 0,
    words: [],
    options: [],
    correctAnswer: null,
    selectedAnswer: null,
    isAnswered: false,
    score: 0,
    isPlaying: false,
    currentAudioContext: null
  },

  onLoad(options) {
    const { groupId } = options
    const groupData = GROUP_DATA.find(item => item.group.group_id === groupId)
    
    if (!groupData) {
      wx.showToast({
        title: '分组数据无效',
        icon: 'error'
      })
      return
    }

    console.log('Group Data:', groupData)

    // 确保 groupData.words 是数组并且有值
    if (!Array.isArray(groupData.words) || groupData.words.length === 0) {
      wx.showToast({
        title: '单词数据无效',
        icon: 'error'
      })
      return
    }

    // 随机打乱单词顺序
    const shuffledWords = this.shuffleArray([...groupData.words])

    this.setData({
      groupId,
      words: shuffledWords
    }, () => {
      this.setupCurrentQuestion()
    })
  },

  // 设置当前题目
  setupCurrentQuestion() {
    const { currentWordIndex, words } = this.data
    const currentWord = words[currentWordIndex]
    
    // 生成选项（包含正确答案和干扰项）
    const options = this.generateOptions(currentWord, words)

    this.setData({
      options,
      correctAnswer: currentWord.word_english,
      selectedAnswer: null,
      isAnswered: false
    })

    // 播放当前单词音频
    this.playWordAudio()
  },

  // 生成选项
  generateOptions(correctWord, allWords) {
    // 从所有单词中随机选择3个不同的单词作为干扰项
    const otherWords = allWords.filter(word => word.word_english !== correctWord.word_english)
    const shuffledOtherWords = this.shuffleArray(otherWords)
    const distractors = shuffledOtherWords.slice(0, 3)
    // 将正确答案和干扰项合并并打乱顺序
    const options = [...distractors, correctWord]
    return this.shuffleArray(options)
  },

  // 数组随机打乱
  shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1))
      let temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
    return array
  },

  // 播放单词音频
  playWordAudio() {
    if (this.data.isPlaying) return
    
    const currentWord = this.data.words[this.data.currentWordIndex]
    const audioContext = wx.createInnerAudioContext()
    
    audioContext.src = currentWord.word_english_audio
    
    this.setData({
      currentAudioContext: audioContext,
      isPlaying: true
    })

    audioContext.onEnded(() => {
      audioContext.destroy()
      this.setData({
        isPlaying: false,
        currentAudioContext: null
      })
    })
    
    audioContext.onError(() => {
      console.error('音频播放失败')
      audioContext.destroy()
      this.setData({
        isPlaying: false,
        currentAudioContext: null
      })
    })
    
    audioContext.play()
  },

  // 处理选项选择
  handleOptionSelect(e) {
    if (this.data.isAnswered) return
    
    const selectedWordId = e.currentTarget.dataset.wordEnglish
    const isCorrect = selectedWordId === this.data.correctAnswer
    const currentWord = this.data.words[this.data.currentWordIndex]

    // 更新测试结果到storage
    storage.updateWordTestResult(
      this.data.groupId,
      currentWord.word_english,
      'listening',
      isCorrect
    )

    this.setData({
      selectedAnswer: selectedWordId,
      isAnswered: true,
      score: this.data.score + (isCorrect ? 1 : 0)
    })
  },

  // 进入下一题
  nextQuestion() {
    const { currentWordIndex, words } = this.data
    
    if (currentWordIndex < words.length - 1) {
      this.setData({
        currentWordIndex: currentWordIndex + 1
      }, () => {
        this.setupCurrentQuestion()
      })
    } else {
      // 测试完成，显示结果
      this.showTestResult()
    }
  },

  // 显示测试结果
  showTestResult() {
    const accuracy = Math.round((this.data.score / this.data.words.length) * 100)
    
    wx.showModal({
      title: '测试完成',
      content: `正确率：${accuracy}%`,
      confirmText: '返回首页',
      cancelText: '重新测试',
      success: (res) => {
        if (res.confirm) {
          wx.navigateBack({
            delta: 2  // 返回首页
          })
        } else {
          this.restartTest()
        }
      }
    })
  },

  // 重新开始测试
  restartTest() {
    this.setData({
      currentWordIndex: 0,
      score: 0,
      words: this.shuffleArray([...this.data.words])
    }, () => {
      this.setupCurrentQuestion()
    })
  },

  onUnload() {
    // 清理音频资源
    if (this.data.currentAudioContext) {
      this.data.currentAudioContext.destroy()
    }
  },

  // 添加新方法
  handleNextClick() {
    if (!this.data.isAnswered) {
      wx.showToast({
        title: '请选择声音对应的图片',
        icon: 'none'
      })
      return
    }
    this.nextQuestion()
  }
}) 